/**
 * Filename: YNTransViewPager.java
 * @author  Firefly
 * @contact postfirefly@163.com
 * @time    2016/6/18 15:09
 */
package com.github.postsanf.yinian.view;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.Scroller;

import java.lang.reflect.Field;

/**
 * 缩放Viewpager
 */
public class YNTransViewPager extends ViewPager
{
	public YNTransViewPager(Context context) {
			super(context);
		}

		public YNTransViewPager(Context context, AttributeSet attrs) {
			super(context, attrs);
		}

		@Override
		public boolean dispatchTouchEvent(MotionEvent ev) {
			if (ev.getAction() == MotionEvent.ACTION_UP) {
				View view = viewOfClickOnScreen(ev);
				if (view != null) {
					setCurrentItem(indexOfChild(view));
				}
			}
			return super.dispatchTouchEvent(ev);
		}

		/**
		 * @param ev
		 * @return
		 */
		private View viewOfClickOnScreen(MotionEvent ev) {
			int childCount = getChildCount();
			int[] location = new int[2];
			for (int i = 0; i < childCount; i++) {
				View v = getChildAt(i);
				v.getLocationOnScreen(location);
				int minX = location[0];
				int minY = getTop();

				int maxX = location[0] + v.getWidth();
				int maxY = getBottom();

				float x = ev.getX();
				float y = ev.getY();

				if ((x > minX && x < maxX) && (y > minY && y < maxY)) {
					return v;
				}
			}
			return null;
		}


	public void setSpeedScroller(int duration) {
		try {
			Field mScroller = null;
			mScroller = ViewPager.class.getDeclaredField("mScroller");
			mScroller.setAccessible(true);
			SpeedScroller scroller = new SpeedScroller(this.getContext(),
					new AccelerateInterpolator());
			mScroller.set(this, scroller);
			scroller.setmDuration(duration);
		}catch(NoSuchFieldException e){

		}catch (IllegalArgumentException e){

		}catch (IllegalAccessException e){

		}
	}

	public class SpeedScroller extends Scroller {
		private int mDuration = 1500;

		public SpeedScroller(Context context) {
			super(context);
		}

		public SpeedScroller(Context context, Interpolator interpolator) {
			super(context, interpolator);
		}

		@Override
		public void startScroll(int startX, int startY, int dx, int dy, int duration) {
			super.startScroll(startX, startY, dx, dy, mDuration);
		}

		@Override
		public void startScroll(int startX, int startY, int dx, int dy) {
			super.startScroll(startX, startY, dx, dy, mDuration);
		}

		public void setmDuration(int time) {
			mDuration = time;
		}

		public int getmDuration() {
			return mDuration;
		}
	}
}